<template>
  <view class="realname-container">
    <scroll-view scroll-y class="scroll-view">
      <view class="content-area">
        <!-- 表单卡片 -->
        <view class="card">
          <view class="card-item">
            <view class="label">姓名：</view>
            <view class="field">
              <uv-input
                v-model="formData.name"
                placeholder="请输入姓名"
                :border="false"
                :clearable="true"
                input-align="left"
                :custom-style="inputStyle"
              />
            </view>
          </view>
          <view class="divider"></view>
          <view class="card-item">
            <view class="label">身份证号：</view>
            <view class="field">
              <uv-input
                v-model="formData.idCard"
                placeholder="请输入身份证号"
                :border="false"
                :clearable="true"
                input-align="left"
                :custom-style="inputStyle"
                maxlength="18"
              />
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部按钮 -->
    <view class="bottom-action">
      <uv-button
        type="primary"
        text="人脸识别"
        size="large"
        :custom-style="buttonStyle"
        @click="handleFaceVerify"
      />
    </view>
  </view>
</template>

<script setup lang="ts">
  import { reactive ,ref} from 'vue'
  import { onShow, onUnload } from '@dcloudio/uni-app'
  import { useRequest } from '@/api'
  import { UserInfoManager } from '@/utils/userInfo'
  const { REAL_NAME_AUTH,REAL_NAME_AUTH_RESULT} = useRequest()
  const formData = reactive({
    name: '',
    idCard: ''
  })

  // 输入框样式（浅灰背景、圆角，贴近设计）
  const inputStyle = {
    backgroundColor: '#ffffff',
    padding: '0',
    fontSize: '28rpx',
    color: '#333'
  }

  // 底部按钮样式（参考统一主题）
  const buttonStyle = {
    backgroundColor: '#FF6B35',
    borderColor: '#FF6B35',
    borderRadius: '24rpx',
    height: '88rpx',
    fontSize: '32rpx',
    fontWeight: '600'
  }

  const idCardReg = /^\d{17}[\dXx]$/
  const address = ref('')
  const certifyid = ref('')
  const token = ref('')
  const userId = ref('')
  const polling = ref(false)
  const pollTimer = ref<number | null>(null)
  const pollAttempts = ref(0)
  const MAX_ATTEMPTS = 30
  const POLL_INTERVAL_MS = 2000

  const stopPolling = () => {
    polling.value = false
    if (pollTimer.value) {
      clearInterval(pollTimer.value as any)
      pollTimer.value = null
    }
  }

  const handleResultSuccess = () => {
    stopPolling()
    uni.showToast({ title: '实名认证成功', icon: 'success' })
    setTimeout(() => {
      uni.navigateBack()
    }, 600)
  }

  const handleResultFail = (msg?: string) => {
    stopPolling()
    uni.showToast({ title: msg || '认证失败，请重试', icon: 'none' })
  }

  const isPassResult = (data: any) => {
    if (!data) return false
    const v = String(
      data.verifyStatus ?? data.status ?? data.result ?? data.passed ?? data.code ?? ''
    ).toUpperCase()
    return v === 'PASS' || v === 'SUCCESS' || v === 'OK' || v === '1' || v === 'TRUE'
  }

  const queryAuthResult = async () => {
    if (!certifyid.value || !token.value) return
    try {
      const params = {
        certifyid: certifyid.value,
        token: token.value,
        userId: userId.value,
        isdriver: UserInfoManager.lastrole()
      }
      const res = await REAL_NAME_AUTH_RESULT(params)
      if (res && res.code === 1) {
        if (isPassResult(res.data)) {
          handleResultSuccess()
          return
        }
        const status = String(res.data?.status ?? '').toUpperCase()
        if (status === 'PROCESSING' || status === 'PENDING') {
          // 继续轮询
        } else if (status === 'FAIL' || status === 'FAILED' || status === 'REJECT') {
          handleResultFail(res.data?.msg || '认证未通过')
        }
      } else if (res) {
        handleResultFail(res.msg)
      }
    } catch (e) {
      // 忽略，稍后重试
    }
  }

  const startPolling = () => {
    if (!certifyid.value || !token.value) {
      uni.showToast({ title: '请先发起认证', icon: 'none' })
      return
    }
    stopPolling()
    polling.value = true
    pollAttempts.value = 0
    queryAuthResult()
    pollTimer.value = setInterval(async () => {
      pollAttempts.value += 1
      if (pollAttempts.value >= MAX_ATTEMPTS) {
        handleResultFail('查询超时，请稍后在此页面点击继续查询')
        return
      }
      await queryAuthResult()
    }, POLL_INTERVAL_MS) as any
  }
  const handleFaceVerify = async () => {
    if (!formData.name.trim()) {
      uni.showToast({ title: '请输入姓名', icon: 'none' })
      return
    }
    if (!idCardReg.test(formData.idCard.trim())) {
      uni.showToast({ title: '请输入正确的身份证号', icon: 'none' })
      return
    }
    const params = {
      username: formData.name,
      idcard: formData.idCard,
      isdriver: UserInfoManager.lastrole(),
    }
    const res = await REAL_NAME_AUTH(params)
    if (res.code === 1 && res.data && res.data.data) {
      const d = res.data.data
      address.value = d.address || ''
      certifyid.value = d.certifyid || ''
      token.value = d.token || ''
      userId.value = d.userId || ''

      // 1) 若 address 已包含完整参数，直接打开
      let url = address.value
      if (url && url.indexOf('http') !== 0) {
        // 兜底：无协议时补 http(s)
        url = 'https://' + url
      }

      // 2) 将易云章要求的参数拼接（保持已有参数不丢失）
      const params = []
      if (certifyid.value) params.push(`certifyid=${encodeURIComponent(certifyid.value)}`)
      if (token.value) params.push(`token=${encodeURIComponent(token.value)}`)
      if (userId.value) params.push(`userId=${encodeURIComponent(userId.value)}`)
      const hasQuery = url.indexOf('?') > -1
      const joiner = hasQuery ? '&' : '?'
      const finalUrl = params.length > 0 ? url + joiner + params.join('&') : url

      // 3) 在 APP 使用系统浏览器打开；H5/小程序内则直接跳转
      // #ifdef APP-PLUS
      plus.runtime.openURL(finalUrl)
      // #endif
      // #ifndef APP-PLUS
      window.location.href = finalUrl
      // #endif
      // 打开后开始轮询查询结果
      startPolling()
    }
  }

  // 回到页面时，如已发起认证，则继续轮询
  onShow(() => {
    if (certifyid.value && token.value && !polling.value) {
      startPolling()
    }
  })
  onUnload(() => {
    stopPolling()
  })
</script>

<style lang="scss" scoped>
  .realname-container {
    min-height: 100vh;
    background: #f6f7f9;
    display: flex;
    flex-direction: column;
  }

  .scroll-view {
    flex: 1;
  }

  .content-area {
    padding: 24rpx;
  }

  .card {
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
    padding: 8rpx 24rpx;
  }

  .card-item {
    display: flex;
    align-items: center;
    padding: 24rpx 0;
  }

  .label {
    width: 180rpx;
    font-size: 30rpx;
    color: #333;
    flex-shrink: 0;
  }

  .field {
    flex: 1;
  }

  .divider {
    height: 1rpx;
    background: #f0f0f0;
  }

  .bottom-action {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 32rpx;
    background: #fff;
    box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
  }

  // 占位符与输入字体微调
  :deep(.uv-input__input) {
    font-size: 28rpx !important;
    color: #333 !important;
  }

  :deep(.uv-input__placeholder) {
    color: #b9bec6 !important;
  }
</style>

